package com.hp.Utils;

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserPhoto {
    public static Map<String,Object> uploadPhoto(MultipartFile file, int userId){
        HashMap<String, Object> result = new HashMap<>();
        // 判断文件是否为空
        if (file.isEmpty()){
            result.put("status", 0);
            result.put("msg", "The file is empty.");
            return result;
        }
        String uploadFileName = file.getOriginalFilename();
        // 创建文件实例
        String storageFileName = userId+uploadFileName.substring(uploadFileName.lastIndexOf("."));
//        String storageFilePath = "D:\\houseRent\\images\\"+storageFileName;
        File f =new File("D:\\houseRent\\images\\",storageFileName);
        // 如果文件目录不存在，创建目录
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        // 写入文件
        try{
            file.transferTo(f);
        }catch(Exception e){
            e.printStackTrace();
            result.put("status", 0);
            result.put("msg", "Fail to Write"+storageFileName);
            return result;
        }
        result.put("status", 1);
        result.put("msg", "OK");
        result.put("fileName",storageFileName);
        return result;
    }
}
